package com.siwei.mes.service.experiment.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.siwei.mes.common.query.PageQuery;
import com.siwei.mes.entity.erp.Itemorder;
import com.siwei.mes.entity.experiment.*;
import com.siwei.mes.entity.sync.tc.Waybill;
import com.siwei.mes.entity.system.Equipment;
import com.siwei.mes.entity.system.SupplierCompany;
import com.siwei.mes.entity.system.TemperatureAndHumidity;
import com.siwei.mes.enums.CheckEnum;
import com.siwei.mes.enums.ExperimentStatusEnum;
import com.siwei.mes.enums.MaterialsEnum;
import com.siwei.mes.mapper.erp.ItemorderMapper;
import com.siwei.mes.mapper.experiment.*;
import com.siwei.mes.mapper.materials.SupplierCompanyMapper;
import com.siwei.mes.mapper.materials.SupplierCompanyMaterialsMapper;
import com.siwei.mes.mapper.syncTc.WaybillMapper;
import com.siwei.mes.mapper.system.EquipmentMapper;
import com.siwei.mes.mapper.system.TemperatureAndHumidityMapper;
import com.siwei.mes.service.experiment.ExperimentSampleTakeService;
import com.siwei.mes.service.experiment.ExperimentService;
import com.siwei.mes.service.system.AuthService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

import static com.siwei.mes.common.exception.handler.MessageHandler.assertTrue;

/**
 * 试验台账取样(ExperimentSampleTake)表服务实现类
 *
 * @author linzi
 * @since 2023-12-28 20:47:32
 */
@Service
public class ExperimentSampleTakeServiceImpl implements ExperimentSampleTakeService {
    private static final Logger log = LoggerFactory.getLogger("laboratory");
    @Value("${createrId}")
    private String createrId;
    @Value("${createrName}")
    private String createrName;
    @Resource
    private ExperimentSampleTakeMapper experimentSampleTakeMapper;
    @Resource
    private AuthService authService;
    @Resource
    private ItemorderMapper itemorderMapper;
    @Resource
    private ExperimentMapper experimentMapper;
    @Resource
    private EquipmentMapper equipmentMapper;
    @Resource
    private TemperatureAndHumidityMapper temperatureAndHumidityMapper;
    @Resource
    private ExperimentSampleSmokeMapper experimentSampleSmokeMapper;
    @Resource
    private CheckQuickConfigMapper checkQuickConfigMapper;
    @Resource
    private CheckBatchConfigMapper checkBatchConfigMapper;
    @Resource
    private ExperimentSampleTestProjectMapper experimentSampleTestProjectMapper;
    @Resource
    private ExperimentService experimentService;
    @Resource
    private WaybillMapper waybillMapper;
    @Resource
    private SupplierCompanyMapper supplierCompanyMapper;
    @Resource
    private SupplierCompanyMaterialsMapper supplierCompanyMaterialsMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long create(ExperimentSampleTake entity) {
        Itemorder itemorder = itemorderMapper.loadByItId(entity.getItemorderId());
        assertTrue(itemorder == null, "ERP小票信息不存在");
        Experiment experiment = experimentMapper.loadById(entity.getExperimentId());
        assertTrue(experiment == null, "试验台账信息不存在");
        entity.setSamplePersonId(authService.getLoginUserId());
        entity.setSamplePersonName(authService.getLoginUserName());
        entity.setSampleTime(new Date());
        entity.init(true);
        entity.setItemorderNo(itemorder.getItemorderno());
        experimentSampleTakeMapper.insertSelective(entity);

        /**需要修改对应试验台账的状态*/
        experiment.init(false);
        experiment.setExperimentStatus(ExperimentStatusEnum.IN_TEST.getCode());
        experimentMapper.updateByPrimaryKeySelective(experiment);
        return entity.getId();
    }

    @Override
    public void update(ExperimentSampleTake entity) {
        Itemorder itemorder = itemorderMapper.loadByItId(entity.getItemorderId());
        assertTrue(itemorder == null, "ERP小票信息不存在");
        assertTrue(experimentMapper.loadById(entity.getExperimentId()) == null, "试验台账信息不存在");
        ExperimentSampleTake experimentSampleTake = experimentSampleTakeMapper.selectByPrimaryKey(entity.getId());
        assertTrue(experimentSampleTake == null, "试验台账取样信息不存在");
        entity.init(false);
        entity.setItemorderNo(itemorder.getItemorderno());
        experimentSampleTakeMapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public void delete(Long id) {
        ExperimentSampleTake experimentSampleTake = experimentSampleTakeMapper.selectByPrimaryKey(id);
        assertTrue(experimentSampleTake == null, "试验台账取样信息不存在");
        experimentSampleTakeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public PageInfo<ExperimentSampleTake> getPage(PageQuery<ExperimentSampleTake, ExperimentSampleTake> query) {
        ExperimentSampleTake searchParam = query.getParams();
        return PageHelper.startPage(query.getPageNum(), query.getPageSize())
                .doSelectPageInfo(() -> experimentSampleTakeMapper.getList(searchParam));
    }

    @Override
    public ExperimentSampleTake loadById(Long id) {
        return experimentSampleTakeMapper.loadById(id);
    }

    @Override
    public List<ExperimentSampleTake> getAll(ExperimentSampleTake entity) {
        return experimentSampleTakeMapper.getList(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Experiment insertOrUpdateByExperimentId(ExperimentSampleTake entity) {
        Experiment experiment = experimentMapper.loadById(entity.getExperimentId());
        assertTrue(experiment == null, "试验台账信息不存在");

        Long experimentId = entity.getExperimentId();
        ExperimentSampleTake isExist = experimentSampleTakeMapper.selectByExperimentId(experimentId);

        if (isExist == null) {
            entity.setSamplePersonId(authService.getLoginUserId());
            entity.setSamplePersonName(authService.getLoginUserName());
            /*李总确认 取样时间取试验台账的委托时间*/
            entity.setSampleTime(experiment.getEntrustTime());
            /*experiment.setMoldingTime(DateHelper.getTomorrowDay());
            experiment.setMoldingTime(new Date());*/
            entity.init(true);
            experimentSampleTakeMapper.insertSelective(entity);
        } else {
            entity.setId(isExist.getId());
            entity.init(false);
            /*experiment.setMoldingTime(DateHelper.addDateHour(isExist.getSampleTime(), 24));
            experiment.setMoldingTime(new Date());*/
            experimentSampleTakeMapper.updateByPrimaryKeySelective(entity);
        }
        /**需要修改对应试验台账的状态*/
        experiment.init(false);
        experiment.setExperimentStatus(ExperimentStatusEnum.IN_TEST.getCode());
        /**赋默认值*/
        setExperiment(experiment);

        Long waybillId = entity.getWaybillId();

        String experimentFactory = null;//生产厂家
        String experimentSupplyCompanyName = null;//供应商名称

        if (waybillId != null) {
            Waybill waybill = waybillMapper.selectByWid(waybillId);
            if (waybill != null) {
                experimentFactory = waybill.getFactory();
                experimentSupplyCompanyName = waybill.getSupplyCompanyCompany();
            }
        } else {
            /**没有运单信息说明该试验委托是手动新建的  这里通过之前试验委托保存好的 生产厂家和供货单位去查询*/
            experimentFactory = experiment.getFactory();
            experimentSupplyCompanyName = experiment.getSupplyCompanyName();
        }

        /**这里赋值生产厂家信息 和供应商信息*/
        if (StringUtils.isNotBlank(experimentFactory)) {
            experiment.setFactory(experimentFactory);
            experiment.setFactoryCalled(supplierCompanyMaterialsMapper.getFactoryCalledListByMaterialsType(experiment.getExperimentType(), experimentFactory));
        }

        if (StringUtils.isNotBlank(experimentSupplyCompanyName)) {
            experiment.setSupplyCompanyName(experimentSupplyCompanyName);
            SupplierCompany supplierCompany = supplierCompanyMapper.selectBySupplierName(experimentSupplyCompanyName);
            if (supplierCompany != null) {
                experiment.setSupplyCompanyName(supplierCompany.getErpCompanyName());
                experiment.setSupplyCompanyCalled(supplierCompany.getSupplierAbbreviation());
            }
        }

        experimentMapper.updateByPrimaryKeySelective(experiment);
        return experiment;
        /**判断委托单是否删除了抽样记录，如删除补全对应的数据
         checkExperimentSampleSmoke(experiment);*/
    }

    @Override
    public ExperimentSampleTake selectByExperimentId(Long experimentId) {
        return experimentSampleTakeMapper.selectByExperimentId(experimentId);
    }

    @Override
    public void concreteSample(Long experimentId) {
        log.info("自动试验委托取样操作开始，对应试验委托id：【{}】", experimentId);
        Experiment experiment = experimentMapper.loadById(experimentId);
        if (experiment == null) {
            log.info("试验委托信息不存在，直接跳过！对应试验委托id：【{}】", experimentId);
            return;
        }
        experimentService.accept(experimentId, false);
        log.info("自动接收试验委托成功，试验委托状态为：【{}】，对应试验委托id：【{}】", ExperimentStatusEnum.WAIT_SAMPLING.getName(), experimentId);
        /**默认第一个小票的信息取样*/
        Itemorder itemorder = itemorderMapper.selectOneByExperimentId(experimentId);
        if (itemorder == null) {
            log.info("【{}】生成委托不存在小票，暂不生成取样记录！", experiment.getExperimentNo());
            return;
        }
        ExperimentSampleTake isExist = experimentSampleTakeMapper.selectByExperimentId(experimentId);
        ExperimentSampleTake entity = new ExperimentSampleTake();
        entity.setExperimentId(experimentId);
        entity.setCarNo(itemorder.getCarnumber());
        /**小票目前没有车牌信息，默认给null*/
        entity.setCarCard(null);
        entity.setDriverName(itemorder.getDrivername());
        entity.setItemorderId(itemorder.getItid());
        entity.setItemorderNo(itemorder.getItemorderno());
        entity.setSampleQuantity(0.05d);
        entity.setSampleStatus("正常");
        entity.setMixtable(itemorder.getMixtable());
        if (isExist == null) {
            entity.setSamplePersonId(Long.valueOf(createrId));
            entity.setSamplePersonName(createrName);
            /*李总确认 取样时间取试验台账的委托时间*/
            entity.setSampleTime(experiment.getEntrustTime());
            entity.laboratoryInit(true);
            experimentSampleTakeMapper.insertSelective(entity);
        } else {
            entity.setId(isExist.getId());
            entity.laboratoryInit(false);
            experimentSampleTakeMapper.updateByPrimaryKeySelective(entity);
        }
        log.info("自动取样成功，等于修改试验委托状态为：【{}】，试验委托id：【{}】", ExperimentStatusEnum.IN_TEST.getName(), experimentId);
        /**需要修改对应试验台账的状态*/
        experiment.laboratoryInit(false);
        experiment.setExperimentStatus(ExperimentStatusEnum.IN_TEST.getCode());
        experiment.setMoldingTime(experiment.getEntrustTime());
        experiment.setSamplingPersonId(Long.valueOf(createrId));
        experiment.setSamplingPersonName(createrName);
        /**赋默认值*/
        setExperiment(experiment);
        experimentMapper.updateByPrimaryKeySelective(experiment);
        log.info("自动试验委托取样操作成功，对应试验委托状态为：【{}】，试验委托id：【{}】", ExperimentStatusEnum.IN_TEST.getName(), experimentId);
    }

    private void setExperiment(Experiment experiment) {
        /**获取仪器设备*/
        /*List<Equipment> equipmentInfoList = equipmentMapper.getEquipmentInfo(MaterialsEnum.CONCRETE.getName());
        StringBuilder equipment = new StringBuilder();
        for (Equipment eq : equipmentInfoList) {
            equipment.append(eq.getEquipmentName()).append(",");
        }
        if (equipment.length() > 0) {
            experiment.setEquipment(equipment.deleteCharAt(equipment.length() - 1).toString());
        }*/
        /**获取最后一条含水率配置*/
        TemperatureAndHumidity lastInfo = temperatureAndHumidityMapper.getLastInfo(new TemperatureAndHumidity());
        if (lastInfo != null) {
            experiment.setTemperature(lastInfo.getTemperature());
            experiment.setHumidness(lastInfo.getHumidness());
        }
        experiment.setCuringMode("标准养护");
    }

    private void checkExperimentSampleSmoke(Experiment experiment) {
        /**试验项目code集合*/
        Set<String> testProjectCodeList = new HashSet<>();
        Set<String> entrustExperimentSet = new HashSet<>();// 委托试验名称
        List<ExperimentSampleSmoke> smokeList = experimentSampleSmokeMapper.getList(new ExperimentSampleSmoke().setExperimentId(experiment.getId()));
        if (experiment.getCheckType() == CheckEnum.BATCH.getCode()) {
            /**获取所有批检配置信息*/
            List<CheckBatchConfig> batchConfigList = checkBatchConfigMapper.getList(new CheckBatchConfig().setIsDel(0).setProjectCategory(MaterialsEnum.CONCRETE.getCode()));
            for (CheckBatchConfig batchConfig : batchConfigList) {
                List<String> codeList = Arrays.asList(batchConfig.getTestProjectCode().split(","));
                testProjectCodeList.addAll(codeList);
                List<String> nameList = Arrays.asList(batchConfig.getTestProjectName().split(","));
                entrustExperimentSet.addAll(nameList);
            }
        } else if (experiment.getCheckType() == CheckEnum.QUICK.getCode()) {
            /**获取所有快检配置信息*/
            List<CheckQuickConfig> quickConfigList = checkQuickConfigMapper.select(new CheckQuickConfig().setIsDel(0).setProjectCategory(MaterialsEnum.CONCRETE.getCode()));
            for (CheckQuickConfig quickConfig : quickConfigList) {
                List<String> codeList = Arrays.asList(quickConfig.getTestProjectCode().split(","));
                testProjectCodeList.addAll(codeList);

                List<String> nameList = Arrays.asList(quickConfig.getTestProjectName().split(","));
                entrustExperimentSet.addAll(nameList);
            }
        }

        List<ExperimentSampleSmoke> sampleSmokeList = new ArrayList<>();
        List<ExperimentSampleTestProject> sampleTestProjectList = experimentSampleTestProjectMapper.selectByTestProjectCodeList(testProjectCodeList);
        for (ExperimentSampleTestProject sampleTestProject : sampleTestProjectList) {
            Integer genNumber = sampleTestProject.getGenNumber();// 生成的条数
            JSONObject genJson = sampleTestProject.getGenJson();// 生成对应的json
            if (genJson.isEmpty() || genNumber == null || genNumber == 0) {
                continue;
            }
            ExperimentSampleSmoke sampleSmoke = this.getExperimentSampleSmoke(sampleTestProject, experiment);
            boolean flag = true;
            for (ExperimentSampleSmoke check : smokeList) {
                if (check.getSampleTestProjectCode().equals(sampleSmoke.getSampleTestProjectCode())) {
                    flag = false;
                }
            }
            if (flag) {
                sampleSmokeList.add(sampleSmoke);
            }

        }
        /**保存抽样信息*/
        if (!sampleSmokeList.isEmpty()) {
            experimentSampleSmokeMapper.insertList(sampleSmokeList);
        }
    }

    /**
     * 生成对应抽检信息
     *
     * @param sampleTestProject 抽检试验项目信息
     * @param experiment        试验台账信息
     * @return
     */
    private ExperimentSampleSmoke getExperimentSampleSmoke(ExperimentSampleTestProject sampleTestProject, Experiment experiment) {
        ExperimentSampleSmoke sampleSmoke = new ExperimentSampleSmoke();
        sampleSmoke.setId(null);
        sampleSmoke.erpInit(true);
        sampleSmoke.setExperimentId(experiment.getId());
        sampleSmoke.setSampleTime(new Date());
        sampleSmoke.setSampleTestProjectCode(sampleTestProject.getItemCode());
        sampleSmoke.setSampleTestProjectName(sampleTestProject.getItemName());
        // JSONArray testProjectJsonArray = ExperimentSampleTestProject.payloadJsonArray(sampleTestProject.getGenJson(),sampleTestProject.getGenNumber());
        // sampleSmoke.setSampleTestProjectJson(testProjectJsonArray);
        sampleSmoke.setFreqNumber(sampleTestProject.getFreqNumber());
        sampleSmoke.setFreqUnit(sampleTestProject.getFreqUnit());
        sampleSmoke.setIsTestBlock(1);// 是否是试块 1-是 0-不是
        sampleSmoke.setTestProjectCode(sampleTestProject.getTestCode());
        sampleSmoke.setTestProjectName(sampleTestProject.getTestName());
        sampleSmoke.setSampleUse(sampleTestProject.getTestName());
        sampleSmoke.setSamplePersonName(experiment.getEntrustPersonName());
        sampleSmoke.setDisposerPersonName(experiment.getEntrustPersonName());
        return sampleSmoke;
    }
}
